/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.astro.threeD {
	import com.googlecode.milib.MILibMain;
	import com.googlecode.milib.base.MLBroadcastClass;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.geom.Point;	

	/**
	 * @author Marek Brun
	 */
	public class AutoPerspectiveProjectionOnCenter extends MLBroadcastClass {
		
		static private var instance:AutoPerspectiveProjectionOnCenter;
		private var root:DisplayObject;

		public function AutoPerspectiveProjectionOnCenter(access:Private, root:DisplayObject) {
			this.root=root;
		}
		
		protected function updateStageAlign():void {
			var p:PerspectiveProjection=root.transform.perspectiveProjection;
			p.projectionCenter=new Point(root.stage.stageWidth/2, root.stage.stageHeight/2);
			root.transform.perspectiveProjection=p;
		}
		
		protected function enablE():void {
			updateStageAlign();
			MILibMain.getInstance().getStage().addEventListener(Event.RESIZE, onStageResize);
		}
		
		protected function disableE():void {
			MILibMain.getInstance().getStage().removeEventListener(Event.RESIZE, onStageResize);
		}
		
		static public function getInstance():AutoPerspectiveProjectionOnCenter {
			if(instance) { return instance; }
			else{ throw new Error('Before call AutoPerspectiveProjectionOnCenter.getInstance() you should call AutoPerspectiveProjectionOnCenter.init()'); }
		}
		
		static public function init(root:DisplayObject):void {
			if(!root.transform.perspectiveProjection){
				throw new Error('Passed root object must have perspectiveProjection (root.transform.perspectiveProjection)');
			}
			if(instance) { return; }
			else{ instance=new AutoPerspectiveProjectionOnCenter(null, root);  }
		}
		
		static public function enable():void {
			getInstance().enablE();
		}
		
		static public function disable():void {
			getInstance().disableE();
		}
		
//********************************************************************************************
//		events for AutoPerspectiveProjectionOnCenter
//********************************************************************************************
		protected function onStageResize(event:Event):void {
			updateStageAlign();
		}
		
	}
}
internal class Private {}